<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 5/25 0025
 * Time: 16:01
 */

namespace app\api\controller;


use app\api\model\Gradient;
use app\api\model\Userapp;
use app\api\model\WxEvent;
use app\index\model\Tool;
use app\index\model\Wx;
use think\Controller;
use think\Exception;

class Notify extends Controller
{
    /**
     * 微信NOTIFY TODO 需要重写!!!!
     */
    public function wxnotify()
    {
        if (!isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
            return "error";
        }
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $out_trade_no = $postObj->out_trade_no; //交易单号
        if ($postObj->result_code != "SUCCESS") {
            return "error";
        } else {
            if ($this->checkorder($out_trade_no)) {
                return 'SUCCESS';
            } else {
                return "error";
            }
        }
    }

    /**
     * 检查订单状况并更改
     */
    private function checkorder($out_trade_no)
    {
        if (empty($out_trade_no)) return false;
        $appbuyorder = model("appbuyorder");
        $res = $appbuyorder->where("sn", $out_trade_no)->where("orderstatus", 0)->find();//找到未支付的订单
        if ($res) {
            if ($appbuyorder->isUpdate(true, ["id" => $res["id"]])->save(["orderstatus" => 1])) {
                //修改userapp表中数据
                $userapp = new Userapp();
                $oriinfo = $userapp->where("appid", $res["appid"])->where(["shopid" => $res["shopid"]])->find();
                if ($oriinfo) {
                    $res2 = $userapp->isUpdate(true, ["id" => $oriinfo["id"]])->save([
                        "appid" => $res["appid"],
                        "shopid" => $res["shopid"],
                        "status" => 1,
                        "endtime" => $res["expiretime"]
                    ]);
                } else {
                    $userapp->data([
                        "appid" => $res["appid"],
                        "shopid" => $res["shopid"],
                        "status" => 1,
                        "starttime" => time(),
                        "endtime" => $res["expiretime"]
                    ]);
                    $res2 = $userapp->save();
                }
                return $res2;
            } else {
                return false;
            }
        } else {
            return false;//没找到符合条件的订单
        }
    }

    /**
     * 支付宝NOTIFY  TODO  需要重写
     */
    public function alipaynotify()
    {
        $out_trade_no = $_POST["out_trade_no"]; //交易单号
        $result = $_POST["trade_status"];
        if ($result != "TRADE_SUCCESS") {
            return "error";
        } else {
            if ($this->checkorder($out_trade_no)) {
                return 'SUCCESS';
            } else {
                return "error";
            }
        }
    }

    /**
     * 查询充值列表
     */
    public function getchargelist()
    {
        $jsonp = request()->get("callback");
        $gradient = new Gradient();
        $res = $gradient->getallbysort();
        if (empty($res)) {
            return $jsonp . "(" . json_encode([]) . ")";
        } else {
            return $jsonp . "(" . json_encode($res) . ")";
        }
    }

    /**
     * 生成一个充值订单并返回给安卓
     */
    public function chargeorder()
    {
        $userid = Index::verifytoken(request()->post("token"));
        if (!$userid) {
            return json(["status" => -1, "data" => "", "msg" => "用户鉴权失败"]);
        } else {
            return json(model("Chargeorder")->addorder($userid, request()->post("chargeid"), request()->post("memberno")));
        }
    }

    /**
     * 充值订单服务器通知
     */
    public function chargenotify()
    {
        //TODO
    }

    /**
     * 读取Excel表格
     */
    public function readexcel()
    {
//        if (request()->isPost()) {
//            if (isset($_FILES["import"]) && ($_FILES["import"]["error"] == 0)){
//        $_FILES["import"]["name"]
        $filepath = "template.xlsx";
        $result = Tool::importExcel($filepath, "UTF-8", pathinfo($filepath, PATHINFO_EXTENSION));
        if ($result) {
            if ($result) {
                dump($result);
            } else {
                die("表格为空");
            }
        } else {
            die("表格格式不正确");
        }
//            }
//        } else {
//            $this->display();
//        }
    }

    /**
     * 测试接受文件
     */
    public function test()
    {
        pathinfo("21", PATHINFO_EXTENSION);
        $appid = "wxeab8017b1449af1d";
        $secret = "3d5d24758227182de4f2884a20196ec4";
        $wxmodel = new Wx();
        $access_token = $wxmodel->getAccessToken($appid, $secret);
        $res = $wxmodel->addpoi($access_token);
        dump($res);
        $a = request()->file();
        $a->validate();
        request()->file()->getBasename();
        $url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=$access_token";
        $data = [
            "buffer" => new \CURLFile(realpath("0.jpg"), request()->file("ajaxfile")->getMime(), $_FILES["ajaxfile"]["name"])
        ];
        $uploadres = upload_file_55($url, $data);
        $uploadarr = json_decode($uploadres, true);
        if (isset($uploadarr["url"])) {
            return $uploadarr["url"];
        } else {
            return $uploadarr["errmsg"];
        }
    }

    /**
     * 上传图片到微信服务器
     */
    public function uploadfile()
    {
        header("Access-Control-Allow-Origin: *");
        if (!$_FILES["ajaxfile"]) {
            return json(["status" => 0, "msg" => "不能为空"]);//文件不能为空
        }
        $appid = "wxb629e35f0b63fef2";
        $secret = "fdfb59a03aa782a4222303a73d9f2dc2";
//        $appid="wx28e4cb89c38339a9";
//        $secret="da3cd5af4143517a54f1c15930fa3e66";
        //$appid="wx4591ec1d03ad1c3d";
        //$secret="bb349834243ff07f6cf5d28070c6caf6";
        //$appid="wxeab8017b1449af1d";
        //$secret="3d5d24758227182de4f2884a20196ec4";
        $wxmodel = new Wx();
        $access_token = $wxmodel->getAccessToken($appid, $secret);
        $res = $wxmodel->addpoi($access_token);
        $url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=$access_token";
        $data = [
            "buffer" => new \CURLFile(request()->file("ajaxfile")->getRealPath(), request()->file("ajaxfile")->getMime(), $_FILES["ajaxfile"]["name"])
        ];
        $uploadres = upload_file_55($url, $data);
        $uploadarr = json_decode($uploadres, true);
        if (isset($uploadarr["url"])) {
            return json(["status" => 1, "url" => $uploadarr["url"]]);
        } else {
            return json(["status" => 0, "msg" => $uploadarr["errmsg"]]);
        }
    }
    ####################################################################################################################
    /**
     * 微信服务器消息入口
     * 两种可能
     */
    public function wxmessage()
    {
//        file_put_contents("wxlog/wx".time().".json", json_encode(request()->param()));
        if(isset($_GET["echostr"])){
            $this->valid();
        }else{
            $this->responseMsg();
        }
    }

    /**
     * 验证token
     * wechat php test
     */
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    /**
     * 检查签名
     * @return bool
     */
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = "success";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    //文本消息text
    //图片消息image
    //语言消息voice
    //视频消息video
    //地理位置消息location
    //链接消息link
    //事件消息event
    //get post data, May be due to the different environments
    public function responseMsg()
    {
        try{
            if (!$this->checkSignature()) {
                die("no access");
            }
        }catch (Exception $exception){
            die($exception->getMessage());
        }
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        //extract post data
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            file_put_contents("wxlog/wx".time().".json", json_encode($postObj));
            $MsgType=$postObj->MsgType;//消息类型
            switch ($MsgType){
                case "text":
                    $fromUsername = $postObj->FromUserName;
                    $toUsername = $postObj->ToUserName;
                    $keyword = trim($postObj->Content);
                    $time = time();
                    $textTpl = <<<EOL
                <xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                <FuncFlag>0</FuncFlag>
                </xml>
EOL;
                    if (!empty($keyword)) {
                        $msgType = "text";
                        $contentStr = "Welcome to wechat world!";
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;
                    } else {
                        echo "Input something...";
                    }
                    break;
                case "image":
                    break;
                case "voice":
                    break;
                case "video":
                    break;
                case "location":
                    break;
                case "link":
                    break;
                case "event":
                    //卡券推送事件
                    WxEvent::EventHandle($postObj);
                    break;
                default:
                    echo "";
                    break;
            }
        } else {
            echo "";
            exit;
        }
    }

}